package com.sttk.secreconeclick.bookkeep.fragment;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.CalendarContract;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.sttk.secreconeclick.bookkeep.bean.BillBean;
import com.blankj.utilcode.util.UtilsTransActivity;
import com.lzb.basic.dialog.PermissionExplainDialog;
import com.lzb.basic.utils.SPUtil;
import com.sttk.secreconeclick.bookkeep.BaseNoModelFragment;
import com.sttk.secreconeclick.bookkeep.Content;
import com.sttk.secreconeclick.bookkeep.R;
import com.sttk.secreconeclick.bookkeep.activity.AboutActivity;
import com.sttk.secreconeclick.bookkeep.activity.ManageTypeActivity;
import com.sttk.secreconeclick.bookkeep.activity.OptionSettingActivity;
import com.sttk.secreconeclick.bookkeep.bean.AccountBookBean;
import com.sttk.secreconeclick.bookkeep.databinding.FragmentMyBinding;
import com.sttk.secreconeclick.bookkeep.dialog.SelAccountBookDialog;
import com.sttk.secreconeclick.bookkeep.utils.AppSpUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MyFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MyFragment extends BaseNoModelFragment<FragmentMyBinding> implements View.OnClickListener {

    private static final int REQUEST_CALENDAR_PERMISSION = 1001;
    private static final String REMIND_EVENT_TITLE = "记账提醒";
    private static final String REMIND_EVENT_DESCRIPTION = "记得记录今天的收支情况哦！";

    private boolean isOpenRemind;

    @Override
    protected int onCreate() {
        return R.layout.fragment_my;
    }

    @Override
    protected void initView() {
        mDataBinding.llTypeManage.setOnClickListener(this);
        mDataBinding.llOptionSetting.setOnClickListener(this);
        mDataBinding.ivOpenRemind.setOnClickListener(this);
        mDataBinding.llExportExcel.setOnClickListener(this);
        mDataBinding.llAbout.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.llTypeManage) {//类别管理
            showSelAccountBookDialog();
        } else if (id == R.id.llOptionSetting) {//选项设置
            startActivity(OptionSettingActivity.class);
        } else if (id == R.id.ivOpenRemind) {//记账提醒
            if (!isOpenRemind) {
                // 开启提醒，检查日历权限
                getPermission();
            } else {
                isOpenRemind = false;
                // 关闭提醒，删除日历事件
                deleteRemindEvent();
            }
            mDataBinding.ivOpenRemind.setImageResource(isOpenRemind ? R.drawable.kai : R.drawable.guan);
            SPUtil.putBoolean(mContext, Content.isOpenRemind, isOpenRemind);
        } else if (id == R.id.llExportExcel) {//导出excel
            exportBillToExcel();
        } else if (id == R.id.llAbout) {//关于
            startActivity(AboutActivity.class);
        }
    }

    @Override
    protected void initData() {
        isOpenRemind = SPUtil.getBoolean(mContext, Content.isOpenRemind, false);
        mDataBinding.ivOpenRemind.setImageResource(isOpenRemind ? R.drawable.kai : R.drawable.guan);
    }

    private void showSelAccountBookDialog() {
        SelAccountBookDialog dialog = new SelAccountBookDialog(mContext);
        dialog.setListener(new SelAccountBookDialog.Ilistener() {
            @Override
            public void clickItem(int pos) {
                ManageTypeActivity.accountBookPos = pos;
                startActivity(ManageTypeActivity.class);
            }
        });
        dialog.show();
    }

    private void getPermission() {
        PermissionExplainDialog dialog = new PermissionExplainDialog(mContext);
        dialog.setContent(getString(R.string.get_calender_permission));
        PermissionUtils.permission(Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR).explain(new PermissionUtils.OnExplainListener() {
            @Override
            public void explain(@NonNull UtilsTransActivity activity, @NonNull List<String> denied, @NonNull ShouldRequest shouldRequest) {
                dialog.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        shouldRequest.start(true);
                    }
                }, 500);
            }
        }).callback(new PermissionUtils.SimpleCallback() {
            @Override
            public void onGranted() {
                dialog.dismiss();
                isOpenRemind = true;
                createRemindEvent();
            }

            @Override
            public void onDenied() {
                dialog.dismiss();
            }
        }).request();
    }

    /**
     * 创建记账提醒日历事件
     */
    private void createRemindEvent() {
        try {
            // 获取日历ID
            long calendarId = getDefaultCalendarId();
            if (calendarId == -1) {
                ToastUtils.showShort("未找到可用日历，请先在系统中添加日历账户");
                return;
            }

            // 设置提醒时间为每天21:00
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 21);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);

            // 如果当前时间已经过了今天的21:00，则从明天开始
            Calendar now = Calendar.getInstance();
            if (calendar.before(now)) {
                calendar.add(Calendar.DAY_OF_YEAR, 1);
            }

            ContentValues eventValues = new ContentValues();
            eventValues.put(CalendarContract.Events.DTSTART, calendar.getTimeInMillis());
            eventValues.put(CalendarContract.Events.DTEND, calendar.getTimeInMillis() + 60 * 60 * 1000); // 1小时后结束
            eventValues.put(CalendarContract.Events.TITLE, REMIND_EVENT_TITLE);
            eventValues.put(CalendarContract.Events.DESCRIPTION, REMIND_EVENT_DESCRIPTION);
            eventValues.put(CalendarContract.Events.CALENDAR_ID, calendarId);
            eventValues.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
            eventValues.put(CalendarContract.Events.RRULE, "FREQ=DAILY"); // 每天重复

            // 插入事件
            ContentResolver cr = mContext.getContentResolver();
            Uri eventUri = cr.insert(CalendarContract.Events.CONTENT_URI, eventValues);

            if (eventUri != null) {
                long eventId = Long.parseLong(eventUri.getLastPathSegment());
                // 保存事件ID，便于后续删除
                SPUtil.putLong(mContext, "remind_event_id", eventId);

                // 添加提醒（提前10分钟）
                ContentValues reminderValues = new ContentValues();
                reminderValues.put(CalendarContract.Reminders.EVENT_ID, eventId);
                reminderValues.put(CalendarContract.Reminders.MINUTES, 10);
                reminderValues.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);
                cr.insert(CalendarContract.Reminders.CONTENT_URI, reminderValues);

                ToastUtils.showShort("记账提醒已设置，每天21:00提醒您记账");
            } else {
                ToastUtils.showShort("创建提醒失败，请检查日历权限");
            }
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtils.showShort("创建提醒失败：" + e.getMessage());
        }
    }

    /**
     * 删除记账提醒日历事件
     */
    private void deleteRemindEvent() {
        try {
            long eventId = SPUtil.getLong(mContext, "remind_event_id", -1);
            if (eventId != -1) {
                ContentResolver cr = mContext.getContentResolver();
                Uri deleteUri = Uri.withAppendedPath(CalendarContract.Events.CONTENT_URI, String.valueOf(eventId));
                int rows = cr.delete(deleteUri, null, null);

                if (rows > 0) {
                    SPUtil.putLong(mContext, "remind_event_id", -1);
                    ToastUtils.showShort("记账提醒已关闭");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取默认日历ID
     */
    private long getDefaultCalendarId() {
        Cursor cursor = null;
        try {
            ContentResolver cr = mContext.getContentResolver();
            cursor = cr.query(CalendarContract.Calendars.CONTENT_URI,
                    new String[]{CalendarContract.Calendars._ID},
                    CalendarContract.Calendars.VISIBLE + " = 1",
                    null,
                    CalendarContract.Calendars._ID + " ASC");

            if (cursor != null && cursor.moveToFirst()) {
                return cursor.getLong(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return -1;
    }

    /**
     * 导出账单数据到Excel文件
     */
    private void exportBillToExcel() {
        try {
            // 获取当前账本数据
            AccountBookBean accountBookBean = AppSpUtils.getAccountBookList().get(SPUtil.getInt(mContext, Content.accountBook, 0));
            List<BillBean> billList = accountBookBean.getBillBeanList();

            if (billList == null || billList.isEmpty()) {
                ToastUtils.showShort("当前账本没有账单数据");
                return;
            }

            // 创建Excel工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("账单记录");

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] headers = {"日期", "类型", "金额", "收支", "备注"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 填充数据
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            int rowNum = 1;
            for (BillBean bill : billList) {
                Row row = sheet.createRow(rowNum++);

                // 日期
                Cell dateCell = row.createCell(0);
                dateCell.setCellValue(dateFormat.format(new Date(bill.getDate())));

                // 类型（收入/支出）
//                Cell typeCell = row.createCell(1);
//                typeCell.setCellValue(bill.isIncome() ? "收入" : "支出");

                // 类型名称
                Cell categoryCell = row.createCell(1);
                if (bill.getBillTypeBean() != null) {
                    categoryCell.setCellValue(bill.getBillTypeBean().getName());
                } else {
                    categoryCell.setCellValue("未知类型");
                }

                // 金额
                Cell moneyCell = row.createCell(2);
                moneyCell.setCellValue(bill.getMoney());

                // 收支标识（用于颜色区分）
                Cell incomeFlagCell = row.createCell(3);
                incomeFlagCell.setCellValue(bill.isIncome() ? "收入" : "支出");

                // 备注
                Cell remarkCell = row.createCell(4);
                remarkCell.setCellValue(bill.getRemark() != null ? bill.getRemark() : "");
            }

            // 设置固定列宽（Android环境下autoSizeColumn方法不兼容）
            sheet.setColumnWidth(0, 4000);  // 日期列
            sheet.setColumnWidth(1, 2000);  // 类型列
            sheet.setColumnWidth(2, 3000);  // 分类列
            sheet.setColumnWidth(3, 2500);  // 金额列
            sheet.setColumnWidth(4, 2000);  // 收支柱
            sheet.setColumnWidth(5, 5000);  // 备注列

            // 创建文件名（包含时间戳）
            String fileName = "账单记录_" + accountBookBean.getName() + "_" +
                    new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".xlsx";

            // 获取外部存储目录
//            File exportDir = new File(mContext.getExternalFilesDir(null), "Excel导出");
            File exportDir = new File(PathUtils.getFilesPathExternalFirst() + Content.excel);
            if (!exportDir.exists()) {
                exportDir.mkdirs();
            }

            File file = new File(exportDir, fileName);

            // 写入文件
            FileOutputStream fos = new FileOutputStream(file);
            workbook.write(fos);
            fos.close();
            workbook.close();

            ToastUtils.showShort("Excel文件导出成功：" + file.getAbsolutePath());

        } catch (Exception e) {
            e.printStackTrace();
            ToastUtils.showShort("导出Excel失败：" + e.getMessage());
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CALENDAR_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                // 权限已授予，创建提醒事件
                createRemindEvent();
            } else {
                // 权限被拒绝
                isOpenRemind = false;
                SPUtil.putBoolean(mContext, Content.isOpenRemind, false);
                mDataBinding.ivOpenRemind.setImageResource(R.drawable.guan);
                ToastUtils.showShort("需要日历权限才能设置记账提醒");
            }
        }
    }

}